package com.chatplus.application.web.filter;


import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.web.auditlogger.UrlFilterUtil;
import com.chatplus.application.web.interceptor.AuditLoggerInterceptor;
import com.chatplus.application.web.interceptor.ContentCachingRequestWrapper;
import com.chatplus.application.web.interceptor.XssContentCachingRequestWrapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author chj
 * @date 2022/6/28
 **/
@Component
@WebFilter
@Order(3)
public class AuditLoggerFilter extends HttpFilter {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(AuditLoggerFilter.class);

    private transient UrlFilterUtil urlFilterUtil;

    @Autowired
    public void setUrlFilterUtil(UrlFilterUtil urlFilterUtil) {
        this.urlFilterUtil = urlFilterUtil;
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (urlFilterUtil != null && urlFilterUtil.excludesURL(request)) {
            chain.doFilter(request, response);
            return;
        }
        String contentType = request.getContentType();
        if (contentType != null) {
            // 只有在以下的情况下才会使用流
            if (
                    contentType.contains(AuditLoggerInterceptor.APPLICATION_JSON)
                            || contentType.contains(AuditLoggerInterceptor.TEXT_PLAIN)
                            || contentType.contains(AuditLoggerInterceptor.TEXT_HTML)
            ) {
                HttpServletRequest requestWrapper;
                if (request instanceof XssHttpServletRequestWrapper) {
                    requestWrapper = new XssContentCachingRequestWrapper(request);
                } else {
                    requestWrapper = new ContentCachingRequestWrapper(request);
                }
                chain.doFilter(requestWrapper, response);
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
